
//
//  NSObject+Ivar.swift
//  61.新工程表情键盘
//
//  Created by apple on 16/3/9.
//  Copyright © 2016年 itcast. All rights reserved.
//

import Foundation

/// 返回值对应表
let ivarTypeDict = [":": "SEL", "#": "Class", "@": "id", "*": "char *", "v": "Void", "B": "Bool", "d": "Double", "f": "Float", "Q": "Long", "L": "Long", "S": "Short", "I": "Int", "C": "Char", "q": "Long", "c": "Char", "i": "Int", "s": "Short", "l": "Long"]

extension NSObject {
    class func printIvars() {
        // runtime重要的关键字: class objc
        
        var count: UInt32 = 0
        
        // Ivar
        // cls: 要获取属性的类
        // outCount: 获取到属性的个数
        let ivars = class_copyIvarList(self, &count)
        
        // 遍历获取每个ivar
        for i in 0..<count {
            let ivar = ivars[Int(i)]
            
            // 获取属性名称,  UnsafePointer<Int8>
            let cName = ivar_getName(ivar)
            let name = String(CString: cName, encoding: NSUTF8StringEncoding)
            
            let cType = ivar_getTypeEncoding(ivar)
            var type = String(CString: cType, encoding: NSUTF8StringEncoding)
            
            if let realType = ivarTypeDict[type!] {
                type = realType
            }
            
            print("name: \(name!), type: \(type!)")
        }
        
    }
}